package com.upload.spring.boot.server;


import com.upload.spring.boot.config.ServerConfig;
import com.upload.spring.boot.properties.UploadProperties;
import com.upload.spring.boot.server.UploadCustomizer;
import com.upload.spring.boot.type.UploadType;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;

import static org.apache.commons.lang3.time.DateFormatUtils.format;


/**
 * @author lgc
 * @createDate 2020/7/28 - 17:15
 */
@Data
public class LocalUploadServer implements UploadCustomizer {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private UploadProperties uploadProperties;

    private ServerConfig serverConfig;


    @Override
    public UploadType getUploadType() {
        return UploadType.LOCAL;
    }

    @Override
    public String upload(byte[] uploadBytes, String fileName) {
        String date = format(new Date(), "yyyyMMdd");
        //存放文件路径
        String localDir = getLocalDir(date);
        //创建路径文件夹
        createDirExsit(localDir);
        //文件路径
        String filePath = localDir + File.separator + fileName;
        //本地上传
        bytesToFile(uploadBytes, filePath);
        String result = serverConfig.getUrl() + File.separator + uploadProperties.getLocalPath() + File.separator +date+ File.separator+fileName;
        log.info("文件上传成功，url:{}",result);
        return result;
    }

    private void bytesToFile(byte[] uploadBytes, String filePath) {
        try( BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(new File(filePath)))) {
            bufferedOutputStream.write(uploadBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void createDirExsit(String localDir) {
        File file = new File(localDir);
        if (!file.exists()){
            file.mkdirs();
        }
    }

    private String getLocalDir(String date) {
        String path = null;
        try {
            path = ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        String localPath = uploadProperties.getLocalPath();
        if (StringUtils.isNotBlank(localPath)){
            path += File.separator+"static"+File.separator+localPath+File.separator+date+File.separator;
        }else {
            path += File.separator+"static"+File.separator+"/upload"+File.separator+date+File.separator;
        }
        return path;
    }


}
